package com.xwy.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xwy.usercenter.model.User;
import com.xwy.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.xwy.usercenter.utils.RedisConstants.CPMATCH_PRECACHEJOB_LOCK;
import static com.xwy.usercenter.utils.RedisConstants.CPMATCH_USER_RECOMMEND;

@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    // 重点用户
    private List<Long> mainUserList = Arrays.asList(1L);

    // 每天执行，预热推荐用户,cron表达式控制执行的频率，可以到网上生成
    //@Scheduled(cron = "30 * * * * ?")   //每30s预热一次，这边要改 TODO
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock(CPMATCH_PRECACHEJOB_LOCK);
        try {
            //如果获得锁，则执行数据预热
            //第一个参数为每个服务器每天来执行该预热工作的等待时间，设为0即每天不用等待就
            //抢锁，抢不到当天就不执行预热
            //第二个参数为锁的过期时间（当锁的释放时间设置为-1时，开启了redisson为我们提供的看门狗机制）
            if (lock.tryLock(0, -1L, TimeUnit.MILLISECONDS)){
            //if (lock.tryLock(0, 30000L, TimeUnit.MILLISECONDS)){
                for (Long userId : mainUserList) {
                    //查数据库
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1,20),queryWrapper);
                    String redisKey = CPMATCH_USER_RECOMMEND + userId;
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    //写缓存,30s过期
                    try {
                        valueOperations.set(redisKey,userPage,30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e){
                        log.error("redis set key error",e);
                    }
                }
                /**
                 * 这样的写法存在的问题：
                 * 如果把释放锁写在try里，那么在获取锁后，接下来执行的代码出现了问题
                 * ，就会导致锁不释放了，所以应该放在finally里
                 */
//                //Checks if this lock is held by the current thread
//                //判断当前锁是否是当前的线程拿着的
//                if (lock.isHeldByCurrentThread()){
//                    lock.unlock();
//                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //Checks if this lock is held by the current thread
            //判断当前锁是否是当前的线程拿着的
            if (lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
